package com.feng.util.mail;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.lenovo.lps.log.Log;

public class MailServiceImpl{
	private static final Log log = Log.getInstance(MailServiceImpl.class);
	private MimeMessage mimeMsg = null; // MIME邮件对象
	private Session session = null; // 邮件会话对象
	private Properties props = null; // 系统属性
	private Multipart mp = null; // Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象

	private boolean needProxy = false;
	private String socksproxyhost = "internetproxy.lenovo";
	private String socksproxyport = "8080";
	private MailInfo mail = null;

	public MailServiceImpl(MailInfo mail) throws Exception {
		if(mail != null){
			this.mail = mail;
		}else throw new Exception("MailInfo is not null!");
		props = System.getProperties();
		props.put("mail.smtp.auth", mail.isAuth());
		props.put("mail.smtp.host", mail.getSmtphost()); // 设置SMTP主机
		
		props.put("proxyset", this.needProxy);
		props.put("socksproxyhost", this.socksproxyhost);
		props.put("socksproxyport", this.socksproxyport);
	}

	public boolean sendMail() throws Exception {
		boolean rt = false;
		try {
			this.createMimeMessage();
			log.debug("********Start Send Mail:" + mail.toString());
			rt = this.sendout();
			log.debug("********Send Mail Success************");
		} catch (Exception e) {
			throw new Exception(e);
		}
		return rt;
	}

	private void createMimeMessage() throws Exception {
		try {
			session = Session.getDefaultInstance(props, null); // 获得邮件会话对象
			mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
			mp = new MimeMultipart();
			this.setSubject(mail.getSubject());
			this.setBody(mail.getBody());
			this.setTo(mail.getTo());
			this.setFrom(mail.getFrom());
			// this.addFileAffix("c:\\boot.ini");
			mimeMsg.setContent(mp);
			mimeMsg.saveChanges();
		} catch (Exception e) {
			throw new Exception(e);
		}
	}

	private void setSubject(String mailSubject) throws Exception {
		mimeMsg.setSubject(mailSubject);
	}

	private void setBody(String mailBody) throws Exception {
		BodyPart bp = new MimeBodyPart();
		bp.setContent("<meta http-equiv=Content-Type content=text/html; charset=UTF-8>" + mailBody,"text/html;charset=UTF-8");
		mp.addBodyPart(bp);
	}

	// private void addFileAffix(String filename) throws Exception {
	// BodyPart bp = new MimeBodyPart();
	// FileDataSource fileds = new FileDataSource(filename);
	// bp.setDataHandler(new DataHandler(fileds));
	// bp.setFileName(fileds.getName());
	// mp.addBodyPart(bp);
	// }

	private void setFrom(String from) throws Exception {
		if (from != null)
			mimeMsg.setFrom(new InternetAddress(from)); // 设置发信人
		else
			throw new Exception("MailInfo from is not null!");
	}

	private void setTo(String to) throws Exception {
		if (to != null)
			mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress
				.parse(to));
		else
			throw new Exception("MailInfo to is not null!");
	}

	// private void setCopyTo(String copyto) throws Exception {
	// if (copyto == null)
	// return;
	// mimeMsg.setRecipients(Message.RecipientType.CC,
	// (Address[]) InternetAddress.parse(copyto));
	// }

	private boolean sendout() throws Exception {
		Transport transport = null;
		try {
			transport = session.getTransport("smtp");
			transport.connect((String) props.get("mail.smtp.host"), mail.getUsername(),mail.getPassword());
			transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
			// transport.send(mimeMsg);
			return true;
		} catch (Exception e) {
			throw e;
		} finally {
			try {
				transport.close();
			} catch (Exception e) {
				throw e;
			}
		}
	}

	public static void main(String[] args) throws Exception{
		MailInfo mail = new MailInfo();
		mail.setAuth(true);
		mail.setPassword("aixiziji");
		mail.setSmtphost("smtp.126.com");
		mail.setUsername("zhaofeng987");
		mail.setFrom("zhaofeng987@126.com");
		mail.setTo("249862061@qq.com");
		mail.setCopyToAddress("liubingzhao@use.com.cn");
		
		String emailTitle="应用测试";
		emailTitle=emailTitle.replace("userName", "");
		emailTitle=emailTitle.replace("appName", "");
		mail.setSubject(emailTitle);
		String emailBody = "Ams AddReport测试!";
		emailBody=emailBody.replace("appName", "");
		emailBody=emailBody.replace("reportContent", "");
		emailBody=emailBody.replace("userName", "");
		emailBody=emailBody.replace("userEmailAddress", "249862061@qq.com");
		emailBody=emailBody.replace("sendReportDate", new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
		
		// 应用的连接
		/*String appUrl = "<a href='" + ipconfig.get("ipconfig")
		+ "viewProduct.do?appId=" + reportForm.getAppId()
		+ "'>" + ipconfig.get("ipconfig")
		+ "viewProduct.do?appId=" + reportForm.getAppId()
		+ "</a>";
		emailBody=emailBody.replace("lianjie", appUrl);*/
		
		mail.setBody(emailBody);
		MailServiceImpl mailService = new MailServiceImpl(mail);
		mailService.sendMail();
	}
	
}